package com.siecom.client;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.Handler;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.Theme;
import com.external.siecom.device.SiecomDeviceProtocol;
import com.external.updzt.device.UPDDeviceProtocol;
import com.external.zbk.device.ZBKDeviceProtocol;
import com.google.android.material.snackbar.Snackbar;

import com.siecomzg.algorithm.sm.SMUtil;
import com.siecomzg.bean.BankCardInfoBean;
import com.siecomzg.bean.IdentityInfoBean;
import com.siecomzg.constconfig.ConstDefine;
import com.siecomzg.constconfig.ErrorDefine;
import com.siecomzg.module.EMVParam;
import com.siecomzg.module.EmvOptions;
//import com.siecom.packageinterface.SiecomDevices_218;
import com.siecomzg.tool.ByteTool;
import com.siecomzg.tool.LogUtil;
import com.siecomzg.tool.Point;
import com.siecomzg.transport.CallbackBundle;
import com.siecomzg.transport.ConnectStatusCallback;
import com.siecomzg.transport.DeviceCallback;
import com.siecomzg.transport.SiecomDevice;
import com.siecom.zhq.client.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

/**
 * Created by Administrator on 2015/12/3.
 * 所有的SDK操作都是以SiecomDevice为入口
 * 使用 SiecomTask.TaskCallback 作为回调的方法都能直接在回调方法内操作界面元素，已经封装了handler在界面执行，除非方法中含有Sync字样，否则均是异步方法，不会堵塞主线程
 * 失败回调固定有错误码和描述，默认内部如IO异常、数组越界等常规错误直接用e.hashcode作为错误码，e.getMessage为信息，其余错误则为本sdk自定义错误。如下
 * int code = bundle.getInt("code");
 * String msg = bundle.getString("message");
 * 成功回调的信息则在bundle内，具体类型和数据请参考本类中的使用
 */
public class DeviceActivity extends AppCompatActivity {

    public static int packType = 0 ; // 0 原来的  1 zbk  2 siecom liaoning 3 贵州农商 赞同UPD1080
    private ZBKDeviceProtocol mZBKInstance;
    public SiecomDeviceProtocol mDevice;
    private UPDDeviceProtocol mUPDDevice;

    private static final String TAG = DeviceActivity.class.getSimpleName();
    //UI setting
    public TextView deviceName;
    public TextView deviceMac;
    public TextView deviceVersion;
    public ImageView deviceIcon;
    public TextView power;
    private SmoothProgressBar spb = null;
    //TextSpeaker speaker;//语音朗读
    //身份证UI
    private TextView tv_name, tv_sex, tv_nation, tv_birth, tv_address, tv_id,
            tv_police, tv_validate;
    private ImageView ivPhotoes;
    //指纹扫描动画
    private ImageView scan_line;
    private Animation upAnimation;
    private Animation downAnimation;

    private Dialog dialog;
    private BluetoothDevice device;
    private UsbDevice mUsbDevice;
    private String mType = "";
    private LinearLayout mLinearLayout;
    private MaterialDialog pDialog = null;

    public final static int dis_connect = 0;
    public final static int arpc_ret = 1; //接受同步ARPC接口
    public final static int get_log_ret = 2; //接受同步明细接口
    public final static int write_code_name = 3; //接受同步写入编号接口
    public final static int read_code_name = 4; //接受同步读取编号接口
    public final static int read_uniq_name = 5; //接受同步读取唯一号接口
    public final static int test_psam = 6; //接受测试PSAM卡

    public TextView cardInfoText;//银行卡信息
    public TextView codenameStr;//编号的textView
    public TextView uniqstr;//唯一号的textView
    private long now = 0;

    private static final String[] cardTypeStr = {"IC卡", "非接卡", "磁条卡","自动"};

    private static final String[] encryptTypeStr = {"国际", "国密","不加密"};
    // 主密钥
        private static byte[] master_key = ByteTool.hexStr2Bytes("E477E2869494E8196D302C89293193C5");

//    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "siecom" + File.separator ;

    // 工作密钥
//    private static byte[] work_key = {0x12, 0x34, 0x56, 0x78, (byte) 0x90,
//            (byte) 0xab, (byte) 0xcd, (byte) 0xef, 0x01, 0x02, 0x03, 0x04,
//            0x05, 0x06, 0x07, 0x08};
    private static byte[] work_key = ByteTool.hexStr2Bytes("85F754C57D5F47A76CE580B8712D1F24");
//"1234567890abcdef0102030405060708"
    final String bankCardNo = "62145601000000647";// 卡号 62145601000000647
    final String amount = "123456.00";// 金额显示,只做显示用，有些固件版本并无此功能
    private Handler handler = new Handler();

    public int cardType = ConstDefine.IC_CARD;

    public byte encryptType = ConstDefine.KEY_SM;  // 1-3DES   2-SM4   3- 明文

    public boolean isSetEncrypt = false;
    private int mProgress = 0;
    /**
     * 用于加密轨迹数据的密钥
     */
    private static byte[] sm4key = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
            0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};


    private void initKeySignPad() {

        //这里初始化加密小板
        /**
         * 流程是先由加密芯片生成公私钥对，再去用SM4加密
         *
         */

        SiecomDevice.transSM2PublicKey(new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {

//                Toast.makeText(DeviceActivity.this, bundle.getInt("code") + "-----" + bundle.getString("message"), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(Bundle bundle) {

                String sm2puk = bundle.getString("data");
                String cipher = SMUtil.SM2PubEncrypt(sm4key, sm2puk.substring(0, 64),
                        sm2puk.substring(64, 128), 2);

                SiecomDevice.setSM4PrimaryKey(ByteTool.hexStr2Bytes(cipher), new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {
                        Toast.makeText(DeviceActivity.this, bundle.getInt("code") + "-----" + bundle.getString("message"), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(Bundle bundle) {

                        Toast.makeText(DeviceActivity.this, "密钥校验码-----" + bundle.getString("data"), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                }, 3000, true);


            }

            @Override
            public void onCompleted(Bundle bundle) {

            }
        }, 3000, true);


    }


    class SpinnerSelectedListener implements Spinner.OnItemSelectedListener {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (cardTypeStr[position].equals("IC卡")) {

                cardType = ConstDefine.IC_CARD;
            }

            if (cardTypeStr[position].equals("非接卡")) {
                cardType = ConstDefine.PIC_CARD;

            }
            if (cardTypeStr[position].equals("磁条卡")) {

                cardType = ConstDefine.MSR_CARD;
            }
            if (cardTypeStr[position].equals("自动")) {

                cardType = ConstDefine.AUTO_CARD;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    }


    private void showOtherDialog() {
        final View view = LayoutInflater.from(DeviceActivity.this).inflate(R.layout.other_layout, null);
        Button writeCodeBtn = (Button) view.findViewById(R.id.write_code_btn);
        Button readCodeBtn = (Button) view.findViewById(R.id.read_code_btn);
        Button readSnBtn = (Button) view.findViewById(R.id.read_sn_btn);
        final EditText codename = (EditText) view.findViewById(R.id.code_name_str);
        codenameStr = (TextView) view.findViewById(R.id.code_text);
        uniqstr = (TextView) view.findViewById(R.id.sn_text);
        final TextView info_text = (TextView) view.findViewById(R.id.info_text);
        Button update_btn = (Button) view.findViewById(R.id.update_btn);
        Button reset_btn = (Button) view.findViewById(R.id.reset_btn);
        Button finger_ver_btn = (Button) view.findViewById(R.id.finger_ver_btn);
        Button testPsam1Btn = (Button) view.findViewById(R.id.testPasm1_btn);
        Button testPsam2Btn = (Button) view.findViewById(R.id.testPasm2_btn);
        Button testLightBtn = (Button) view.findViewById(R.id.test_light_btn);
        Button testSerialBtn = (Button) view.findViewById(R.id.test_serial_btn);
        Button btnApdu = (Button) view.findViewById(R.id.test_apdu_btn);

        android.widget.Button btnReadSocial = (android.widget.Button) view.findViewById(R.id.btn_read_social);
        btnReadSocial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                info_text.setText("");
                SiecomDevice.readSocialCard(0, "", new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {

                    }

                    @Override
                    public void onSuccess(Bundle bundle) {
                        String data = bundle.getString("data");
                        LogUtil.e(TAG,"" + data);
//                        uniqstr.setText(data);
                        info_text.setText("读取结果：" + data);
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                },20*1000,true);
            }
        });
        /**
         * 测试apdu
         */
        btnApdu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LogUtil.e(TAG,"time == " + System.currentTimeMillis());
                if (packType == 3){
                    byte[] atr = new byte[20];
                    JSONObject jb = mUPDDevice.iccPowerOn(0,10*1000,atr);
                    try {
                        int ret = jb.getInt("code");
                        LogUtil.e(TAG,"iccPowerOn == " + jb.toString() + "---- atr == " + ByteTool.byte2hex(atr));
                        if (ret != 0) return;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    String cmd = "00a40400"; // 选择文件
                    String send = "0f 73 78 31 2e 73 68 2e c9 e7 bb e1 b1 a3 d5 cf";
                    send = "";
                    send = send.replace(" ","");
                    int len = send.length()/2;
                    String retStr = mUPDDevice.iccCose(cmd + "00"+String.format("%02x",len) + send + "0100");
                    LogUtil.e(TAG,"iccCose == " + retStr);
//                    send = "0084000000000008";
//                    for (int i = 0; i < 5; i++) {
//                        retStr = mUPDDevice.iccCose(send);
//                        LogUtil.e(TAG,"iccCose == " + retStr);
//                    }

//                    mUPDDevice.iccPowerOff(0);
                }
            }
        });
        /**
         * 测试psam卡
         */
        testPsam1Btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SiecomDevice.testPsam("1", new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {
                        Toast.makeText(DeviceActivity.this, "PSAM1 失败!", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(Bundle bundle) {

                        Toast.makeText(DeviceActivity.this, "PSAM1 OK!", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                }, 3000, true);

            }
        });
        testPsam2Btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SiecomDevice.testPsam("2", new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {
                        Toast.makeText(DeviceActivity.this, "PSAM2 失败!", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(Bundle bundle) {

                        Toast.makeText(DeviceActivity.this, "PSAM2 OK!", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                }, 3000, true);


            }
        });

        testLightBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (packType == 0){
                    SiecomDevice.testLight(new DeviceCallback() {
                        @Override
                        public void onStart() {

                        }

                        @Override
                        public void onError(Bundle bundle) {

                        }

                        @Override
                        public void onSuccess(Bundle bundle) {

                        }

                        @Override
                        public void onCompleted(Bundle bundle) {

                        }
                    },10*1000,true);
                }
                if (packType == 1){
                    mZBKInstance.makeBeep(1,10);
                    mZBKInstance.ledOnOrOff(0,1,0);
                    JSONObject jb = mZBKInstance.getKeypadID();
                    LogUtil.e(TAG,"mInstance.getKeypadID() = " + jb.toString());
                }
                if (packType == 3){
//                    mUPDDevice.makeBeep(1,10);
//                    //测试led灯
//                    for (int i = 0; i < 4; i++) {
//                        mUPDDevice.ledOnOrOff(i,1,0);
//                        mUPDDevice.ledOnOrOff(i,2,0);
//                    }
                    //测试声音控制
//                    for (int i = 0; i < 10; i++) {
//                        mUPDDevice.makeVoice(i);
//                        try {
//                            Thread.sleep(3000);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                    }
                    JSONObject jb = mUPDDevice.getKeypadID();
                    LogUtil.e(TAG,"mUPDDevice.getKeypadID() = " + jb.toString());
                }


            }
        });
        testSerialBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


            }
        });


        finger_ver_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SiecomDevice.readFingerVersion(new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {

                    }

                    @Override
                    public void onSuccess(Bundle bundle) {

                        Toast.makeText(DeviceActivity.this, "version:" + bundle.getString("data"), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                }, 6000, true);


            }
        });
        Button test_btn = (Button) view.findViewById(R.id.test_btn);
        test_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (packType == 1){
                    int battaryInfo[] = mZBKInstance.getBatteryInfo();
                    LogUtil.e(TAG,"有无电池：" +battaryInfo[0] +  "--充电方向：" + battaryInfo[1] + "电量：" +battaryInfo[2] );
                }
                if (packType == 2){
                    int battaryInfo[] = mDevice.getBatteryInfo();
                    LogUtil.e(TAG,"有无电池2：" +battaryInfo[0] +  "--充电方向：" + battaryInfo[1] + "电量：" +battaryInfo[2] );
                }
                if (packType == 3){
                   JSONObject jbout = mUPDDevice.getDeviceVersion(10*1000);
                    LogUtil.e(TAG,"getDeviceVersion：" + jbout.toString() );
//                    JSONObject jbout = mUPDDevice.getDeviceState("FR",10*1000);
//                    LogUtil.e(TAG,"getDeviceState：" + jbout.toString() );
                }

            }
        });
        /**
         * 改成升级固件了
         */
        update_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Map<String, Integer> images = new HashMap<String, Integer>();
                images.put(OpenFileDialog.sRoot, R.drawable.filedialog_root);
                images.put(OpenFileDialog.sParent, R.drawable.filedialog_folder_up);
                images.put(OpenFileDialog.sFolder, R.drawable.filedialog_folder);
                images.put("bin", R.drawable.filedialog_file);
                images.put("apk",R.mipmap.ic_launcher);

                dialog = OpenFileDialog.createDialog(DeviceActivity.this, "Select File", new CallbackBundle() {
                            @Override
                            public void callback(Bundle bundle) {
                                final String openfilePath = bundle.getString("path");
                                Log.d("openfilePath", "open file path: *" + openfilePath + "*");
                                if (openfilePath.endsWith("bin") || openfilePath.endsWith("apk") || openfilePath.endsWith("zip")) {
                                    if (packType == 3){
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                mUPDDevice.updateDevice(openfilePath);
                                            }
                                        }).start();

                                    }else
                                    SiecomDevice.updateFw(openfilePath, new DeviceCallback() {
                                        @Override
                                        public void onStart() {
//                                            Log.e("updateFw", "onStart");
                                        }

                                        @Override
                                        public void onError(Bundle bundle) {
                                            Log.e("updateFw", "onError");
                                            Toast.makeText(DeviceActivity.this, "升级失败，请重新升级", Toast.LENGTH_SHORT).show();

                                        }

                                        @Override
                                        public void onSuccess(Bundle bundle) {
//                                            LogUtil.e(TAG, "updateFw onSuccess ==" + bundle.getInt("data"));
                                            // Toast.makeText(DeviceActivity.this,"固件升级进度："+bundle.getInt("data")+"%",Toast.LENGTH_SHORT).show();
                                            mProgress = bundle.getInt("data");
                                            info_text.setText("升级进度：" + mProgress + "%");
                                            if((mProgress % 10) == 0){
                                                Toast.makeText(DeviceActivity.this, "正在升级，请不要关闭电源和其他操作", Toast.LENGTH_SHORT).show();
                                            }
                                        }

                                        @Override
                                        public void onCompleted(Bundle bundle) {
                                            Log.e("updateFw", "onCompleted");
                                            Toast.makeText(DeviceActivity.this, "固件升级完成", Toast.LENGTH_SHORT).show();
                                            info_text.setText("升级完成");
                                        }
                                    }, 5*60*1000, true);

                                }

                            }
                        },
                        "",
                        images);
                dialog.show();


            }
        });

        reset_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                disConnectBlueDevice();
                //测试升级
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        String path = "/sdcard/Download/update.apk";
//                        boolean isSuc = mUPDDevice.updateDevice(path);
//                        LogUtil.e(TAG,"isSuc=====" + isSuc);
//                    }
//                }).start();

                //测试 重置密码
                int ret = mUPDDevice.reset();
                LogUtil.e(TAG,"ret == " + ret);
            }
        });

        writeCodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = codename.getText().toString().trim();
                LogUtil.e(TAG,"name==" + name);
                if(TextUtils.isEmpty(name) || name.length() > 64){
                    Toast.makeText(DeviceActivity.this,"编码长度需要1-64位",Toast.LENGTH_SHORT).show();
                    return;
                }
                SiecomDevice.setCodeName(name, new DeviceCallback() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onError(Bundle bundle) {

                    }

                    @Override
                    public void onSuccess(Bundle bundle) {
                        Toast.makeText(DeviceActivity.this, "写入编号成功", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                }, 3000, true);

            }

        });
        readCodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SiecomDevice.getCodeName(new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {

                    }

                    @Override
                    public void onSuccess(Bundle bundle) {
                        String codeStr = bundle.getString("data");

                        codeStr = codeStr.replace(" ","");
                        codenameStr.setText(codeStr);
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                }, 3000, true);

            }
        });
        readSnBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                String id = mInstance.getDeviceSerialID();
//                LogUtil.e(TAG,"读到设备ID：" + id);
//                if(id != null){
//                    return;
//                }
                SiecomDevice.getDeviceSN(new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {

                    }

                    @Override
                    public void onSuccess(Bundle bundle) {

                        uniqstr.setText(bundle.getString("data"));
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                }, 6000, true);


            }

        });
        pDialog = new MaterialDialog.Builder(DeviceActivity.this)
                .theme(Theme.LIGHT)
                .title(R.string.other)
                .customView(view, true)
                .positiveText(R.string.no)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {

                        dismissDialog();

                    }
                })
                .dismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {


                    }
                })
                .build();
        pDialog.show();

    }

//    private void updateBin() {
//        final View view = LayoutInflater.from(DeviceActivity.this).inflate(R.layout.other_layout, null);
//        final TextView info_text = (TextView) view.findViewById(R.id.info_text);
//        Map<String, Integer> images = new HashMap<String, Integer>();
//        images.put(OpenFileDialog.sRoot, R.drawable.filedialog_root);
//        images.put(OpenFileDialog.sParent, R.drawable.filedialog_folder_up);
//        images.put(OpenFileDialog.sFolder, R.drawable.filedialog_folder);
//        images.put("bin", R.drawable.filedialog_file);
//        dialog = OpenFileDialog.createDialog(DeviceActivity.this, "Select File", new CallbackBundle() {
//                    @Override
//                    public void callback(Bundle bundle) {
//                        String openfilePath = bundle.getString("path");
//                        Log.d("openfilePath", "open file path: *" + openfilePath + "*");
//                        if (openfilePath.endsWith("bin")) {
//                            SiecomDevice.updateFw(openfilePath, new DeviceCallback() {
//                                @Override
//                                public void onStart() {
//
//                                    Log.e("updateFw", "onStart");
//
//                                    Toast.makeText(DeviceActivity.this, "开始升级，请不要关闭电源和其他操作", Toast.LENGTH_SHORT).show();
//
//                                }
//
//                                @Override
//                                public void onError(Bundle bundle) {
//                                    Log.e("updateFw", "onError");
//                                    Toast.makeText(DeviceActivity.this, "固件升级失败，请重新升级", Toast.LENGTH_SHORT).show();
//
//                                }
//
//                                @Override
//                                public void onSuccess(Bundle bundle) {
//                                    Log.e("updateFw", "==" + bundle.getInt("data"));
//                                    // Toast.makeText(DeviceActivity.this,"固件升级进度："+bundle.getInt("data")+"%",Toast.LENGTH_SHORT).show();
//                                    info_text.setText("固件升级进度：" + bundle.getInt("data") + "%");
//                                }
//
//                                @Override
//                                public void onCompleted(Bundle bundle) {
//                                    Log.e("updateFw", "onCompleted");
//                                    Toast.makeText(DeviceActivity.this, "固件升级完成", Toast.LENGTH_SHORT).show();
//                                    info_text.setText("固件升级完成");
//                                }
//                            }, 300000, true);
//
//
//                        }
//
//                    }
//                },
//                ".bin;",
//                images);
//        dialog.show();
//    }


    private void showCardDialog() {
        //默认就是第一个
        dismissDialog();
        final View view = LayoutInflater.from(DeviceActivity.this).inflate(R.layout.card_dialog_layout, null);
        Button read_card_btn = (Button) view.findViewById(R.id.read_card_btn);
        final Button arpcBtn = (Button) view.findViewById(R.id.arpc_btn);
        final Button getLogBtn = (Button) view.findViewById(R.id.get_log_btn);
        Spinner spinner = (Spinner) view.findViewById(R.id.card_list_spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(DeviceActivity.this, android.R.layout.simple_spinner_item, cardTypeStr);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        cardInfoText = (TextView) view.findViewById(R.id.card_info_text);
        final TextView cardTypeText = (TextView) view.findViewById(R.id.card_type_text);
        final TextView cardNoText = (TextView) view.findViewById(R.id.card_no_text);
        //添加事件Spinner事件监听
        spinner.setOnItemSelectedListener(new SpinnerSelectedListener());

        pDialog = new MaterialDialog.Builder(DeviceActivity.this)
                .theme(Theme.LIGHT)
                .customView(view, true)
                .title(R.string.readCard)
                .positiveText(R.string.no)
                .cancelable(false)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                        dismissDialog();
                        if (packType == 3){
                            int ret = -1;
                            if (cardType == ConstDefine.MSR_CARD)
                                ret = mUPDDevice.cancelReadMCCard();
                            if (cardType == ConstDefine.IC_CARD || cardType == ConstDefine.PIC_CARD || cardType == ConstDefine.AUTO_CARD)
                                ret = mUPDDevice.cancelReadICCard();
                            LogUtil.e(TAG,"ret == " + ret);
                        }else
                        SiecomDevice.cancelCurrentTask(new DeviceCallback() {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onError(Bundle bundle) {

                            }

                            @Override
                            public void onSuccess(Bundle bundle) {

                                Toast.makeText(DeviceActivity.this, bundle.getString("data"), Toast.LENGTH_SHORT).show();

                            }

                            @Override
                            public void onCompleted(Bundle bundle) {

                            }
                        }, 2000, true);
                    }
                })
                .dismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {

                        cardType = ConstDefine.IC_CARD;

                    }
                })
                .build();
        pDialog.show();

        read_card_btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.e("cardType:", cardType + "----");


                EmvOptions options = new EmvOptions();
                EMVParam emvParam = new EMVParam();
                byte[] MerchCateCode = new byte[2];
                MerchCateCode[0] = 0x00;
                MerchCateCode[1] = 0x01;
                emvParam.setMerchCateCode(MerchCateCode);
                String MerchId = "123456789012345";
                emvParam.setMerchId(MerchId.getBytes());
                emvParam.setMerchName("EMV LIBRARY".getBytes());
                emvParam.setTermId("12345678".getBytes());
                emvParam.setTerminalType((byte) 0x22);
                emvParam.setSurportPSESel((byte) 0x01);
                byte[] Capability = {(byte) 0xE0, (byte) 0x60, (byte) 0xC8};
                emvParam.setCapability(Capability);
                byte[] ExCapability = {(byte) 0x60, (byte) 0x00, (byte) 0xF0,
                        (byte) 0x20, (byte) 0x01};
                emvParam.setExCapability(ExCapability);
                byte[] CountryCode = {(byte) 0x01, (byte) 0x56};
                byte[] TransCurrCode = {(byte) 0x01, (byte) 0x56};
                byte[] ReferCurrCode = {(byte) 0x01, (byte) 0x56};
                emvParam.setCountryCode(CountryCode);
                emvParam.setTransCurrCode(TransCurrCode);
                emvParam.setTransCurrExp((byte) 0x02);
                emvParam.setReferCurrCode(CountryCode);
                emvParam.setCL_TransLimit(100000);
                emvParam.setTransType((byte) 0x00);// 交易类型
                byte[] TermTransQuali = {0x24, 0x00, 0x00, (byte) 0x80};
                emvParam.setTermTransQuali(TermTransQuali);
                emvParam.setCL_bStatusCheck((byte) 0x00);
                emvParam.setCL_CVMLimit(10000);
                emvParam.setCL_FloorLimit(20000);

                emvParam.setECTSI((byte) 0x01);
                emvParam.setEC_TermLimit(10000);
                emvParam.setEC_bTermLimitCheck((byte) 0x01);

                options.setEmvParam(emvParam);
                options.setAuthorizedAmount(1);

                SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");// 设置日期格式
                String time = df.format(new Date());
                options.setTime(time);
                options.setTransNo(1);

//                String[]   wantTags = new String[]{"5A", "57", "9F26", "9F27", "9F10", "9F37", "9F36",
//                        "95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03",
//                        "9F33", "9F34", "9F35", "9F1E", "4F", "5F34"};
                String[] wantTags = {"5A", "57", "5F20", "9F62", "9F61", "9F1F", "9F79",
                        "9F77", "5F24", "5F34", "9F26", "9F27", "9F10", "9F37", "9F36",
                        "95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03", "9F33",
                        "9F34"};

                now = System.currentTimeMillis();

                DeviceCallback deviceCallback = new DeviceCallback() {
                    @Override
                    public void onStart() {

                        cardTypeText.setText("");
                        cardNoText.setText("");
                        cardInfoText.setText("");

                    }

                    @Override
                    public void onError(Bundle bundle) {
                        int code = bundle.getInt("code");
                        String msg = bundle.getString("message");

                        //speaker.speak("error：" + code);
                        mFailCount++;
//                        pDialog.setTitle("成功"+ mSuccessCount+"次，"+ "失败" + mFailCount + "次");
                        Snackbar.make(view, "err:" + code + "--" + msg, Snackbar.LENGTH_LONG).setAction("Action", null).show();
                    }

                    @Override
                    public void onSuccess(Bundle bundle) {
                        mSuccessCount++;
                        final BankCardInfoBean bean = bundle.getParcelable("data");
                        long finish = System.currentTimeMillis();
                        Snackbar.make(view, getResources().getString(R.string.readComplete) + ":useTime:" + (finish - now) + "ms", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        if (bean.cardType == ConstDefine.IC_CARD) {
                            cardTypeText.setText(getResources().getString(R.string.ICC));
                            cardNoText.setText(bean.cardNo);
                            cardInfoText.setText(bean.ICChipData);

                        } else if (bean.cardType == ConstDefine.PIC_CARD) {

                            cardTypeText.setText(getResources().getString(R.string.PICC));
                            cardNoText.setText(bean.cardNo);
                            cardInfoText.setText(bean.ICChipData);

                        } else if (bean.cardType == ConstDefine.MSR_CARD) {
                            cardTypeText.setText(getResources().getString(R.string.MSR));
                            cardNoText.setText(bean.cardNo);
                            cardInfoText.setText("tk1:" + bean.oneMagneticTrack + "\r\n" + "tk2:" + bean.twoMagneticTrack + "\r\n" + "tk3:" + bean.threeMagneticTrack);

                        }
//                        pDialog.setTitle("成功"+ mSuccessCount+"次，"+ "失败" + mFailCount + "次");

                        //如果不是磁卡可以获取交易的明细和做arpc
                        if (bean.cardType != ConstDefine.MSR_CARD) {
                            arpcBtn.setVisibility(View.VISIBLE);
                            getLogBtn.setVisibility(View.VISIBLE);

                            arpcBtn.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    final String arpc = "910A2501EEC5A3FDBF563030";//91开头，脚本是72开头
                                    final String script = "7251860F04DA9F790A000000000000A4B17D6D860F04DA9F770A0000001000008C09E6BF862D04DC010C2870229F61123433313232313139383830373136313231589F6201105F2006C5CBB0D8D3EEA168BB5A";

                                    cardInfoText.setText("TestARPC:" + arpc + "\r\n" + "TestScript:" + script);
                                    SiecomDevice.ARPCExecuteScript(bean.cardType, arpc, script, new DeviceCallback() {
                                        @Override
                                        public void onStart() {

                                        }

                                        @Override
                                        public void onError(Bundle bundle) {

                                            cardInfoText.setText("ARPC 返回:" + bundle.getInt("code") + "\r\n");
                                        }

                                        @Override
                                        public void onSuccess(Bundle bundle) {

                                            cardInfoText.setText("ret:" + bundle.getString("result"));


                                        }

                                        @Override
                                        public void onCompleted(Bundle bundle) {

                                            arpcBtn.setVisibility(View.VISIBLE);

                                        }
                                    }, 10000, true);


                                }
                            });
                            getLogBtn.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    //获取交易明细
                                    cardInfoText.setText("正在获取交易明细");
                                    byte[] details = new byte[1024*4];
                                    int ret = mZBKInstance.getICCTradeDetail(cardType,"",details);
                                    if(ret ==0){
                                        LogUtil.e(TAG,"读取成功 日志为：" + new String(details));
                                    }else {
                                        LogUtil.e(TAG,"日志读取失败");
                                    }
//                                    SiecomDevice.readTradeLog(bean.cardType, new DeviceCallback() {
//                                        @Override
//                                        public void onStart() {
//
//                                            arpcBtn.setVisibility(View.INVISIBLE);
//
//                                        }
//
//                                        @Override
//                                        public void onError(Bundle bundle) {
//
////                                            final String arpc = "910A2501EEC5A3FDBF563030";//91开头，脚本是72开头
////                                            final String script = "7251860F04DA9F790A000000000000A4B17D6D860F04DA9F770A0000001000008C09E6BF862D04DC010C2870229F61123433313232313139383830373136313231589F6201105F2006C5CBB0D8D3EEA168BB5A";
////
////                                            cardInfoText.setText("TestARPC:" + arpc + "\r\n" + "TestScript:" + script);
//                                            cardInfoText.setText(bundle.getString("message") + bundle.getInt("code"));
//
//                                        }
//
//                                        @Override
//                                        public void onSuccess(Bundle bundle) {
//                                            List<TradeLogBean> list = bundle.getParcelableArrayList("data");
//                                            StringBuffer buf = new StringBuffer();
//                                            for (TradeLogBean bean : list) {
//
//                                                Log.e("logbean:", bean.getMerchName());
//                                                buf.append("交易记录—时间：" + bean.getDate() + bean.getTime() + "—金额:" + bean.getAmount() + "—商户：" + bean.getMerchName() + "\r\n");
//                                            }
//                                            cardInfoText.setText("交易明细：\r\n" + buf);
//                                        }
//
//                                        @Override
//                                        public void onCompleted(Bundle bundle) {
//
//                                        }
//                                    }, 30000, true);


                                }

                            });
                        } else {

                            arpcBtn.setVisibility(View.INVISIBLE);
                            getLogBtn.setVisibility(View.INVISIBLE);
                        }


                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

//                        now = System.currentTimeMillis();
                    }

                };
                if(packType == 0){
                    SiecomDevice.readBankCard(cardType,deviceCallback,options,wantTags, 30000, true);
                }else if (packType == 2){
                    if (cardType == 0){
                        JSONObject jbInfo = mDevice.pbocReadAppDataAsync(1,"","ABCDEFGHIJKL","",5);
                        LogUtil.e(TAG,"mDevice.pbocReadAppDataAsync == " + jbInfo.toString());
                        byte[] arpc = new byte[1024];
                        byte[] tradeAppData = new byte[1024];
                        JSONObject jb = mDevice.pbocGenerateUnionpayField55(1,"","",arpc,tradeAppData);
                        if (jb != null)
                            LogUtil.e(TAG,"mDevice.pbocGenerateUnionpayField55 == " + jb.toString());
                    }
                    if (cardType == 2){
                        JSONObject jbInfo = mDevice.pbocReadAppDataAsync(2,"","ABCDEFGHIJKL","",5);
                        LogUtil.e(TAG,"mDevice.pbocReadAppDataAsync == " + jbInfo.toString());
                        byte[] arpc = new byte[1024];
                        byte[] tradeAppData = new byte[1024];
                        JSONObject jb = mDevice.pbocGenerateUnionpayField55(2,"","",arpc,tradeAppData);
                        if (jb != null)
                            LogUtil.e(TAG,"mDevice.pbocGenerateUnionpayField55 2 == " + jb.toString());
                    }

                    if (cardType == 1){ //磁条卡
                        JSONObject jb = mDevice.readCardTrack23Async(23,30);
                        if (jb != null)
                            LogUtil.e(TAG,"mDevice.readCardTrack23Async == " + jb.toString());
                    }

                }else if (packType == 3){ // UPD1080

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if(cardType == 0){
                                String taglist = "ABCDEFGHIJKL";
//                                JSONObject jb = mUPDDevice.getICCardInfo(cardType,"",taglist,30*1000);
//                                LogUtil.e(TAG,"mInstance.getICCardInfo == " + jb.toString());
                                //测试 55域
                                JSONObject jb = mUPDDevice.getICCardInfoAndARQC(cardType,"",taglist,"",20*1000);
                                LogUtil.e(TAG,"mInstance.getICCardInfoAndARQC == " + jb.toString());

                                //测试数据
                                String ARPC = "010203040506070803037251860F04DA9F790A000000000000A4B17D6D860F04DA9F770A0000001000008C09E6BF862D04DC010C2870229F61123433313232313139383830373136313231589F6201105F2006C5CBB0D8D3EEA168BB5A";
                                String ScriptStr = "7251860F04DA9F790A000000000000A4B17D6D860F04DA9F770A0000001000008C09E6BF862D04DC010C2870229F61123433313232313139383830373136313231589F6201105F2006C5CBB0D8D3EEA168BB5A";

                                //贵州农信测试数据
                                // [{"strTxData":"9F2608EA8D99024C88726D9F2701809F101307010103A0A010040A010000100000AFA58FA69F3704000000009F36020015950500000008009A031201019C01605F3401009F02060000000000045F2A02015682027C009F1A0201569F03060000000000049F330320A1009F34033F00005A0A6217793307071111110F9F13020000",
                                // "strARPC":"5F2A02015672189F180400000001860F04DA9F790A00000009990048BC544882027C00910A989FB7628FD5BAC13030950500000008009A031201019C01609F02060000000000049F03060000000000049F101307010103A0A010040A010000100000AFA58FA69F1A0201569F2608EA8D99024C88726D9F2701809F330320A1009F34033F00009F360200159F370400000000","CDol2":"","timeout":10}]
                                String strTxData = "9F2608EA8D99024C88726D9F2701809F101307010103A0A010040A010000100000AFA58FA69F3704000000009F36020015950500000008009A031201019C01605F3401009F02060000000000045F2A02015682027C009F1A0201569F03060000000000049F330320A1009F34033F00005A0A6217793307071111110F9F13020000";
                                ARPC = "5F2A02015672189F180400000001860F04DA9F790A00000009990048BC544882027C00910A989FB7628FD5BAC13030950500000008009A031201019C01609F02060000000000049F03060000000000049F101307010103A0A010040A010000100000AFA58FA69F1A0201569F2608EA8D99024C88726D9F2701809F330320A1009F34033F00009F360200159F370400000000";
                                //测试数据2
                                ARPC = "5F2A02015672189F180400000001860F04DA9F790A0000000196006FE4E35182027C00910A0F6268F4AF30CAA73030950508800460009A032301239C01009F02060000000000009F03060000000000009F101307010103602C00040A0100000197000483DBBC9F1A0201569F26084080F652CA529F469F2701809F3303E0F0C89F360200F89F3704B906EEC6";

                                //ARPC校验
                                jb = mUPDDevice.ARPC_ExeICScript(strTxData,ARPC,"",30+"");
                                LogUtil.e(TAG,"mUPDDevice.ARPC_ExeICScript == " + jb.toString());
//                        getLogBtn.setVisibility(View.VISIBLE);
//                        getLogBtn.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                //获取交易明细
//                                cardInfoText.setText("正在获取交易明细");
//                                byte[] details = new byte[1024*4];
//                                int ret = mZBKInstance.getICCTradeDetail(cardType,"",details);
//                                if(ret ==0){
//                                    LogUtil.e(TAG,"读取成功 日志为：" + new String(details));
//                                }else {
//                                    LogUtil.e(TAG,"日志读取失败");
//                                }
//                            }
//                        });
                            }
                            if(cardType == 1){ //磁条卡
                                JSONObject jb = mUPDDevice.getMCCardInfo(23,20*1000);
                                if(jb != null){
                                    LogUtil.e(TAG,"读磁卡数据为：" + jb.toString());
                                }else {
                                    LogUtil.e(TAG,"读卡失败");
                                }
                            }
                            if(cardType == 2){ //非接卡
                                String taglist = "ABCDEFGHIJKL";
//                                JSONObject jb = mUPDDevice.getICCardInfo(cardType,"",taglist,30*1000);
//                                LogUtil.e(TAG,"mInstance.getICCardInfo == " + jb.toString());
                                JSONObject jb = mUPDDevice.getICCardInfoAndARQC(cardType,"",taglist,"",20*1000);
                                LogUtil.e(TAG,"mUPDDevice.getICCardInfoAndARQC == " + jb.toString());

                                String strTxData = "9F2608EA8D99024C88726D9F2701809F101307010103A0A010040A010000100000AFA58FA69F3704000000009F36020015950500000008009A031201019C01605F3401009F02060000000000045F2A02015682027C009F1A0201569F03060000000000049F330320A1009F34033F00005A0A6217793307071111110F9F13020000";
                                String ARPC = "5F2A02015672189F180400000001860F04DA9F790A00000009990048BC544882027C00910A989FB7628FD5BAC13030950500000008009A031201019C01609F02060000000000049F03060000000000049F101307010103A0A010040A010000100000AFA58FA69F1A0201569F2608EA8D99024C88726D9F2701809F330320A1009F34033F00009F360200159F370400000000";

                                //ARPC校验
                                jb = mUPDDevice.ARPC_ExeICScript(strTxData,ARPC,"",30+"");
                                LogUtil.e(TAG,"mUPDDevice.ARPC_ExeICScript == " + jb.toString());

                            }
                            if(cardType == 3){ //自动
                                String taglist = "ABCDEFGHIJKL";
                                JSONObject jb = mUPDDevice.getICCardInfoAndARQC(cardType,"",taglist,"",30*1000);
                                LogUtil.e(TAG,"mInstance.getICCardInfoAndARQC == " + jb.toString());

                                jb = mUPDDevice.getPassword(bankCardNo,30,2,1,1,6,6,true);
                                try {
                                    if (jb.getInt("code") == 0){
                                        String strTxData = "9F2608EA8D99024C88726D9F2701809F101307010103A0A010040A010000100000AFA58FA69F3704000000009F36020015950500000008009A031201019C01605F3401009F02060000000000045F2A02015682027C009F1A0201569F03060000000000049F330320A1009F34033F00005A0A6217793307071111110F9F13020000";
                                        String ARPC = "5F2A02015672189F180400000001860F04DA9F790A00000009990048BC544882027C00910A989FB7628FD5BAC13030950500000008009A031201019C01609F02060000000000049F03060000000000049F101307010103A0A010040A010000100000AFA58FA69F1A0201569F2608EA8D99024C88726D9F2701809F330320A1009F34033F00009F360200159F370400000000";

                                        //ARPC校验
                                        jb = mUPDDevice.ARPC_ExeICScript(strTxData,ARPC,"",30+"");
                                        LogUtil.e(TAG,"mUPDDevice.ARPC_ExeICScript == " + jb.toString());
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                            }
                        }
                    }).start();



                }
                else {
                    if(cardType == 0){
//                    String taglist = "ABCDEFGHIJK";
//                    JSONObject jb = mInstance.getICCardInfo(cardType,"",taglist,30*1000);
//                    LogUtil.e(TAG,"mInstance.getICCardInfo == " + jb.toString());
                    //测试 55域
                    JSONObject jb = mZBKInstance.get55FieldData(06,0,20*1000);
                    LogUtil.e(TAG,"mInstance.get55FieldData == " + jb.toString());
                    getLogBtn.setVisibility(View.VISIBLE);
                    getLogBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            //获取交易明细
                            cardInfoText.setText("正在获取交易明细");
                            byte[] details = new byte[1024*4];
                            int ret = mZBKInstance.getICCTradeDetail(cardType,"",details);
                            if(ret ==0){
                                LogUtil.e(TAG,"读取成功 日志为：" + new String(details));
                            }else {
                                LogUtil.e(TAG,"日志读取失败");
                            }
                        }
                    });
                }
                if(cardType == 1){ //磁条卡
                    JSONObject jb = mZBKInstance.getMCCardInfo(23,20*1000);
                    if(jb != null){
                        LogUtil.e(TAG,"读磁卡数据为：" + jb.toString());
                    }else {
                        LogUtil.e(TAG,"读卡失败");
                    }
                }
                if(cardType == 2){ //非接卡
                    String taglist = "ABCDEFGHIJK";
                    JSONObject jb = mZBKInstance.getICCardInfo(cardType,"",taglist,30*1000);
                    LogUtil.e(TAG,"mInstance.getICCardInfo == " + jb.toString());
                }
                if(cardType == 3){ //自动
                    String taglist = "ABCDEFGHIJK";
                    JSONObject jb = mZBKInstance.getICCardInfo(cardType,"",taglist,30*1000);
                    LogUtil.e(TAG,"mInstance.getICCardInfo == " + jb.toString());
                }
                }

            }
        });

    }

    class EncryptSelectedListener implements Spinner.OnItemSelectedListener {


        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            if (encryptTypeStr[position].equals("国际")) {

                encryptType = ConstDefine.KEY_3DES;
            }
            if (encryptTypeStr[position].equals("国密")) {

                encryptType = ConstDefine.KEY_SM;

            }
            if(encryptTypeStr[position].equals("不加密")){

                encryptType = ConstDefine.KEY_NOENCRYPTION;
            }

            isSetEncrypt = true;
//            setEncrypt();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    }

    public void setEncrypt() {
        int endType = 0;
        int mkeyIndex = 0;
        int wkeyIndex = 0;
        SiecomDevice.keySetEncryptMode(encryptType,endType,mkeyIndex,wkeyIndex, new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {
                int code = bundle.getInt("code");
                String msg = bundle.getString("message");


//                Toast.makeText(DeviceActivity.this, "err:" + code + "--" + msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(Bundle bundle) {

//                Toast.makeText(DeviceActivity.this, getResources().getString(R.string.set_encrypt), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCompleted(Bundle bundle) {

            }
        }, 3000, true);

    }

    /**
     * 密码键盘的界面
     */
    private void showKeyDialog() {

        encryptType = ConstDefine.KEY_3DES; //默认为第一个
        final View view = LayoutInflater.from(DeviceActivity.this).inflate(R.layout.keypad_dialog, null);
//        Toast.makeText(DeviceActivity.this, getResources().getString(R.string.need_set_mode), Toast.LENGTH_SHORT).show();

        TextView main_key = (TextView) view.findViewById(R.id.main_key_text);
        main_key.setText(getResources().getString(R.string.main_key) + ":" + ByteTool.byte2hex(master_key));
        TextView work_key_text = (TextView) view.findViewById(R.id.work_key_text);
        work_key_text.setText(getResources().getString(R.string.work_key) + ":" + ByteTool.byte2hex(work_key));
        Button input_mkey_btn = (Button) view.findViewById(R.id.input_mkey_btn);
        Button btnChangeMain = (Button) view.findViewById(R.id.btn_change_main);
        Button input_wkey_btn = (Button) view.findViewById(R.id.input_wkey_btn);
        Button pubEncMainBtn = (Button) view.findViewById(R.id.btn_test_sm2_encrypt_main);
        Button inputMacKeyBtn = (Button) view.findViewById(R.id.input_mackey_btn);
        Button calcMacBtn = (Button) view.findViewById(R.id.btn_test_calc_mac);
        final TextView cardNo = (TextView) view.findViewById(R.id.card_no_str);
        TextView amount_text = (TextView) view.findViewById(R.id.amount_str);
        cardNo.setText(getResources().getString(R.string.card_no) + ":" + bankCardNo);
        amount_text.setText(getResources().getString(R.string.amount) + ":" + amount);
        @SuppressLint("WrongViewCast") final AppCompatEditText click_input = (AppCompatEditText) view.findViewById(R.id.click_input);
        click_input.setInputType(InputType.TYPE_NULL);
        click_input.requestFocus();
        Spinner spinner = (Spinner) view.findViewById(R.id.encrypt_spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(DeviceActivity.this, android.R.layout.simple_spinner_item, encryptTypeStr);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new EncryptSelectedListener());
//        pubEncMainBtn.setVisibility(View.INVISIBLE);

        final int mainIndex = 1;
        final int workIndex = 2;
        pubEncMainBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //==========测试公钥加密主密钥=====================================================
                String pubX = "DD7A70215B5353A43697E172CB110FC9B67AD593A60BA22F8197A8FDBDC54D6C";
                String pubY = "7C47F34134A40CF525D36DC2F76634C48A4700389B7F991AC8164A5AE5429DF0";
                String pri = "2E56817BCF2B0CA0B0C3FF0282EC33ECCD77AE33A9159AD5B0718B5D28DEA8CF";
                String pubKey = pubX + pubY;
//                JSONObject jb = mZBKInstance.getSessionKey(1,4,pubKey);
//                LogUtil.e(TAG,"mInstance.getSessionKey = " + jb);
                SiecomDevice.generateProtectKey("00", pubKey, 1, new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {

                    }

                    @Override
                    public void onSuccess(Bundle bundle) {
                        String resStr = bundle.getString("data");
                        LogUtil.e(TAG,"generateProtectKey onSuccess : " + resStr);
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                },10*1000,true);
                //==========测试重置秘钥=====================================================
//                int ret = mZBKInstance.resetPassword(10*1000);
//                LogUtil.e(TAG,"mInstance.resetPassword = " + ret);
                //==========测试重置秘钥=====================================================
            }
        });
        btnChangeMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String changeMainKey = "8B56B2DBD1F37C76717CA48C77AF7B11";  //check: F659FDED57BF6723E1ACA09868D7B22C  明文：716CCFE92331E1B04B0006EFFB8182E5
                SiecomDevice.inputMainKey(0 + "", changeMainKey,  encryptType,0x81, new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {

                    }

                    @Override
                    public void onSuccess(Bundle bundle) {
                        String result = bundle.getString("data");
                        LogUtil.e(TAG,"result == " + result);
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                },10*1000,true);
            }
        });
        inputMacKeyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String inMackey = "22BC3833503557EDAA1EE0A9032AA3FD";// 名文：D8EF902E67674E98F113780B8B8AAB73   check :A86D056BDBEE476C3CB3A75D3861C6A5

                SiecomDevice.inputWorkKey(0 + "", 0 + "", inMackey,
                        2,0x81, 2, new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {

                    }

                    @Override
                    public void onSuccess(Bundle bundle) {
                        String result = bundle.getString("data");
                        LogUtil.e(TAG,"result == " + result);
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                },10*1000,true);
            }
        });

        calcMacBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String testMacData = "MMS2023033068014555679962285622000240405";   // 计算结果：4F5AA50AF978AE2CE19EE5490901AB86
//                testMacData = ByteTool.byte2hex(testMacData.getBytes());
                SiecomDevice.calcMac(0, 0, 1, testMacData, new DeviceCallback() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onError(Bundle bundle) {

                    }

                    @Override
                    public void onSuccess(Bundle bundle) {
                        String result = bundle.getString("data");
                        LogUtil.e(TAG,"result == " + result);
                    }

                    @Override
                    public void onCompleted(Bundle bundle) {

                    }
                },10*1000,true);
            }
        });
        input_mkey_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                if (!isSetEncrypt) {
//
//                    setEncrypt();
//                    isSetEncrypt = true;
//                }
                if (packType == 3){
                    String key = "716CCFE92331E1B04B0006EFFB8182E5";
                    String check = "F659FDED57BF6723E1ACA09868D7B22C";
                    int ret = mUPDDevice.downloadMasterKey(encryptType,5*1000,mainIndex,key,"12B1C3A9AC2B8DB6");
                    LogUtil.e(TAG,"downloadMasterKey ret == " + ret);
                }
                if (packType == 0){
                    String pubKey = "99104B11B45C4BD7D1A7BED2A68698D337DA6127BBC14C727B79DC21E86878DE17808CBB08A152BB85D37CB5D67943C7ADF1C07D9C8D205C1978FC97F876F84E";
                    final String priKey = "D107E4B726CB660E3D674DD83DB3BB6FBC6431B93598DDF2DC946E967585F50C";

                    DeviceCallback deviceCallback = new DeviceCallback() {
                        @Override
                        public void onStart() {
                            Snackbar.make(view, getResources().getString(R.string.input_key_start), Snackbar.LENGTH_LONG).setAction("Action", null).show();

                        }

                        @Override
                        public void onError(Bundle bundle) {

                            int code = bundle.getInt("code");
                            String msg = bundle.getString("message");

                            Snackbar.make(view, "err:" + code + "--" + msg, Snackbar.LENGTH_LONG).setAction("Action", null).show();

                        }

                        @Override
                        public void onSuccess(Bundle bundle) {
                            Snackbar.make(view, getResources().getString(R.string.input_main_succ), Snackbar.LENGTH_LONG).setAction("Action", null).show();
                            String enData = bundle.getString("data");
                            LogUtil.e(TAG,"返回数据是：" + enData);
//                            if(!TextUtils.isEmpty(enData)){
//                                SiecomDevice.sm2Decrypt(priKey, enData,1);
//                            }
                        }

                        @Override
                        public void onCompleted(Bundle bundle) {

                        }

                    };
                    String mainKey = "5746383E2C850DE99E89BF19B0EFC280"; //check:  AE950815B7A289D08F8CD608DA3EADF4
                    // mode  0x00明文写入  0x81 解密写入  0x01加密写入
                    SiecomDevice.inputMainKey("00", mainKey,encryptType,0x00, deviceCallback, 3000, true);
                    //测试SM2公钥加密主密钥

//                    SiecomDevice.generateProtectKey("00",pubKey,1,deviceCallback,3000,true);

                }

            }
        });

        input_wkey_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (!isSetEncrypt) {
//
//                    setEncrypt();
//                    isSetEncrypt = true;
//
//                }
                if (packType == 3){
                    String workKey = "2DB741D26B5EE917F70A4F6E3E600DEA";
                    int ret = mUPDDevice.downloadWorkKey(encryptType,10*1000,mainIndex,workIndex,workKey,"0C1A7497A8E023260C1A7497A8E02326");
                    LogUtil.e(TAG,"downloadWorkKey ret == " + ret);
                }
                else
                    SiecomDevice.inputWorkKey("00", "00", ByteTool.byte2hex(work_key),encryptType,0x81, new DeviceCallback() {
                        @Override
                        public void onStart() {
                            Snackbar.make(view, getResources().getString(R.string.input_key_start), Snackbar.LENGTH_LONG).setAction("Action", null).show();

                        }

                        @Override
                        public void onError(Bundle bundle) {

                            int code = bundle.getInt("code");
                            String msg = bundle.getString("message");

                            Snackbar.make(view, "err:" + code + "--" + msg, Snackbar.LENGTH_LONG).setAction("Action", null).show();

                        }

                        @Override
                        public void onSuccess(Bundle bundle) {

                            Snackbar.make(view, getResources().getString(R.string.input_work_succ), Snackbar.LENGTH_LONG).setAction("Action", null).show();

                        }

                        @Override
                        public void onCompleted(Bundle bundle) {

                        }

                    }, 3000, true);


            }
        });

        click_input.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                int inputTimes = 1;
                Log.e("click_input", "----");
                DeviceCallback deviceCallback = new DeviceCallback() {
                    @Override
                    public void onStart() {
                        Snackbar.make(view, getResources().getString(R.string.start_input), Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        click_input.setText("");

                    }

                    @Override
                    public void onError(Bundle bundle) {
                        int code = bundle.getInt("code");
                        String msg = bundle.getString("message");
                        if (code == ErrorDefine.CANCEL_INPUT) {
                            click_input.setText("");
                            Snackbar.make(view, getResources().getString(R.string.input_cancel), Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        }
                        if (code == ErrorDefine.KEY_TIME_OUT) {
                            click_input.setText("");
                            Snackbar.make(view, getResources().getString(R.string.input_timeout), Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        }
                        if (code == ErrorDefine.LENGTH_ERR) {
                            click_input.setText("");
                            Snackbar.make(view, getResources().getString(R.string.input_length), Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        }
                        if (code == ErrorDefine.SET_ENCRYPT_ERR) {
                            click_input.setText("");
                            Snackbar.make(view, getResources().getString(R.string.input_length), Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        }
                        if (code == ErrorDefine.KEY_INPUT_ERR) {
                            click_input.setText("");
                            Snackbar.make(view, getResources().getString(R.string.input_err), Snackbar.LENGTH_LONG).setAction("Action", null).show();

                        }
                    }

                    @Override
                    public void onSuccess(Bundle bundle) {
                        int num = bundle.getInt("data");
                        StringBuffer buf = new StringBuffer();
                        for (int i = 0; i < num; i++)
                            buf.append("*");

                        click_input.setText(buf.toString());

                    }

                    @Override
                    public void onCompleted(Bundle bundle) {
                        //  LogUtil.e("pwd:", bundle.getString("data"));
                        click_input.setText(bundle.getString("data"));
                        Log.e("TAG","密文返回："+ bundle.getString("data"));
                    }
                };

                if (packType == 0){
                    SiecomDevice.startInputPwd(bankCardNo, "00", "00", encryptType, "06",0,deviceCallback , 60000, inputTimes,true);
                }else if(packType == 2){
                    JSONObject jb = mDevice.getPinBlockExAsync(bankCardNo,5,1,1,1,6,6);
                    LogUtil.e(TAG,"mDevice.getPassword == " + jb.toString());
                }else if (packType == 1){
                    JSONObject jb = mZBKInstance.getPassword(bankCardNo,30*1000,0,encryptType,1,6,6);
                    LogUtil.e(TAG,"mInstance.getPassword == " + jb.toString());
                }else if (packType == 3){

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (encryptType == 3){ //明文
                                    JSONObject jb = mUPDDevice.getVerification(30 , 7);
                                    LogUtil.e(TAG,"mInstance.getVerification == " + jb.toString());
//                                    JSONObject jb = mUPDDevice.getPassword(bankCardNo, 30, workIndex, 0, 2, 6, 6, false);
//                                    LogUtil.e(TAG,"mInstance.getPassword == " + jb.toString());
                                }else {
                                    JSONObject jb = mUPDDevice.getPassword(bankCardNo, 30, workIndex, encryptType, 2, 6, 12, true);
                                    LogUtil.e(TAG,"mInstance.getPassword == " + jb.toString());
                                }

                            }
                        }).start();


                }

            }
        });
        String str = getResources().getString(R.string.no);
        pDialog = new MaterialDialog.Builder(DeviceActivity.this)
                .theme(Theme.LIGHT)
                .title(R.string.keyPin)
                .customView(view, true)
                .positiveText(str)
                .cancelable(false)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {

                        dismissDialog();
                        if (packType == 3){
                           int ret = mUPDDevice.cancelReadPin();
                            LogUtil.e(TAG,"ret == " + ret);
                        }else
                        SiecomDevice.cancelCurrentTask(new DeviceCallback() {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onError(Bundle bundle) {

                            }

                            @Override
                            public void onSuccess(Bundle bundle) {

                                Toast.makeText(DeviceActivity.this, bundle.getString("data"), Toast.LENGTH_SHORT).show();

                            }

                            @Override
                            public void onCompleted(Bundle bundle) {

                            }
                        }, 2000, true);
                    }
                })
                .dismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {

                    }
                })
                .build();
        pDialog.show();


    }


    /**
     * 读取指纹特征码
     */
    public void readFingerPrint() {
        mFailCount=0;
        mSuccessCount = 0;

        final DeviceCallback deviceCallback = new DeviceCallback() {
            @Override
            public void onStart() {

                View view = LayoutInflater.from(DeviceActivity.this).inflate(R.layout.layout_finger_scan, null);
                scan_line = (ImageView) view.findViewById(R.id.lockscreen_scan_line);
                upAnimation = AnimationUtils.loadAnimation(DeviceActivity.this, R.anim.push_up_in);
                upAnimation.setFillAfter(true);
                upAnimation.setAnimationListener(new UpAnimationOnListener());

                downAnimation = AnimationUtils.loadAnimation(DeviceActivity.this, R.anim.push_up_out);
                downAnimation.setFillAfter(true);
                downAnimation.setAnimationListener(new DownAnimationOnListener());
                scan_line.startAnimation(downAnimation);
                pDialog = new MaterialDialog.Builder(DeviceActivity.this)
                        .theme(Theme.DARK)
                        .customView(view, true)
                        .title(R.string.finger_scan)
                        .positiveText(R.string.no)
                        .cancelable(false)
                        .dismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                /**
                                 * 取消任务；
                                 */
                                SiecomDevice.cancelCurrentTask(new DeviceCallback() {
                                    @Override
                                    public void onStart() {

                                    }

                                    @Override
                                    public void onError(Bundle bundle) {
                                    }

                                    @Override
                                    public void onSuccess(Bundle bundle) {
                                        Toast.makeText(DeviceActivity.this, bundle.getString("data"), Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onCompleted(Bundle bundle) {
                                    }
                                }, 2000, true);


                            }
                        })
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                                dismissDialog();
                                Snackbar.make(mLinearLayout, "取消指纹后再启动最长可能需要5~7秒", Snackbar.LENGTH_LONG).setAction("Action", null).show();

                            }
                        })
                        .build();
                pDialog.show();
            }

            @Override
            public void onError(Bundle bundle) {
                mFailCount++;
                dismissDialog();
                Snackbar.make(mLinearLayout, bundle.getString("message"), Snackbar.LENGTH_LONG).setAction("Action", null).show();
            }

            @Override
            public void onSuccess(Bundle bundle) {
                mSuccessCount ++;
                dismissDialog();
                /**
                 * 获取到指纹特征码，默认使用Base64转一下
                 */
                String fingerCode = bundle.getString("data");

                Log.e("fingerPrint:", fingerCode);

                dismissDialog();

                pDialog = new MaterialDialog.Builder(DeviceActivity.this)
                        .theme(Theme.DARK)
                        .title(R.string.finger_code)
                        .content(getResources().getString(R.string.your_finger) + ":" + fingerCode)
                        .positiveText(R.string.sure)
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                                dismissDialog();
                            }
                        })
                        .build();
                pDialog.show();


            }

            @Override
            public void onCompleted(Bundle bundle) {
//                pDialog.setTitle("成功"+ mSuccessCount+"次，"+ "失败" + mFailCount + "次");
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (packType == 0)
                    SiecomDevice.readFingerFeature(deviceCallback, 30000, true);
                else if (packType == 1){
                    JSONObject jb =  mZBKInstance.getFpInfo(30*1000);
                    LogUtil.e(TAG,"mInstance.getFpInfo == " + jb.toString());
                }else if (packType == 2){
                    JSONObject jb =  mDevice.getFeatureDataAsync(10);
                    LogUtil.e(TAG,"mDevice.getFeatureDataAsync == " + jb.toString());
                }else if (packType == 3){
                    mUPDDevice.cancelReadFp();
                    JSONObject jb =  mUPDDevice.getFpInfo(20);
                    LogUtil.e(TAG,"mUPDDevice.getFpInfo == " + jb.toString());
                }
            }
        }).start();


    }

    int mSuccessCount = 0,mFailCount = 0;
    /**
     * 读取身份证
     */
    public void readIDcard() {
        Log.e("read", "readIDcard");

        mSuccessCount = 0;
        mFailCount = 0;
        now = System.currentTimeMillis();
        DeviceCallback taskCallback = new DeviceCallback() {
            @Override
            public void onStart() {

                Snackbar.make(mLinearLayout, getResources().getString(R.string.read_id), Snackbar.LENGTH_LONG).setAction("Action", null).show();

                pDialog = new MaterialDialog.Builder(DeviceActivity.this)
                        .title(R.string.read_id)
                        .content(R.string.please_wait)
                        .progress(true, 0)
                        .progressIndeterminateStyle(true)
                        .positiveText(R.string.no)
                        .cancelable(false)
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                                dismissDialog();
                                SiecomDevice.cancelCurrentTask(new DeviceCallback() {
                                    @Override
                                    public void onStart() {

                                    }

                                    @Override
                                    public void onError(Bundle bundle) {

                                    }

                                    @Override
                                    public void onSuccess(Bundle bundle) {

                                        Toast.makeText(DeviceActivity.this, bundle.getString("data"), Toast.LENGTH_SHORT).show();

                                    }

                                    @Override
                                    public void onCompleted(Bundle bundle) {

                                    }
                                }, 2000, true);

                            }
                        })
                        .dismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {

                            }
                        })
                        .build();

                if (!pDialog.isShowing()) {
                    pDialog.show();
                }
            }

            @Override
            public void onSuccess(Bundle bundle) {
                mSuccessCount ++;
                long fin = System.currentTimeMillis();
                Toast.makeText(DeviceActivity.this, "useTime:" + (fin - now) + "ms", Toast.LENGTH_SHORT).show();
                //获取bean
                IdentityInfoBean bean = bundle.getParcelable("data");

                dismissDialog();

                View view = LayoutInflater.from(DeviceActivity.this).inflate(R.layout.draw_idcard, null);
                tv_name = (TextView) view.findViewById(R.id.name);
                tv_sex = (TextView) view.findViewById(R.id.sex);
                tv_nation = (TextView) view.findViewById(R.id.nation);
                tv_birth = (TextView) view.findViewById(R.id.birth);
                tv_address = (TextView) view.findViewById(R.id.address);
                tv_id = (TextView) view.findViewById(R.id.id);
                tv_police = (TextView) view.findViewById(R.id.police);
                tv_validate = (TextView) view.findViewById(R.id.validate);
                ivPhotoes = (ImageView) view.findViewById(R.id.touxiang);

                tv_name.setText(bean.fullName);
                tv_sex.setText(bean.sex);
                tv_nation.setText(bean.nation);
                StringBuffer buffer = new StringBuffer();
                buffer.append(bean.birthday.substring(0, 4)).append("        ").append(bean.birthday.substring(4, 6)).append("     ").append(bean.birthday.substring(6, 8));

                tv_birth.setText(buffer.toString());
                tv_address.setText(bean.idAddr);
                tv_id.setText(bean.idNo);
                tv_police.setText(bean.idOrg);
                tv_validate.setText(bean.beginDate + "-" + bean.endDate);

                ivPhotoes.setImageBitmap(bean.icon);
                String str = getResources().getString(R.string.no_finger);
//                str = "成功" + mSuccessCount + "次,失败" + mFailCount + "次" ;
                if (bean.fingerStr != null) {
                    str = getResources().getString(R.string.has_finger);
                    Toast.makeText(DeviceActivity.this, bean.fingerStr, Toast.LENGTH_SHORT).show();

                }
                pDialog = new MaterialDialog.Builder(DeviceActivity.this)
                        .theme(Theme.DARK)
                        .customView(view, true)
                        .positiveText(str)
                        .onPositive(new MaterialDialog.SingleButtonCallback() {

                            @Override
                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                                dismissDialog();
                            }
                        })
                        .build();
                pDialog.show();
            }

            @Override
            public void onCompleted(Bundle bundle) {
                now = System.currentTimeMillis();
                LogUtil.e("身份证------",  "onCompleted!!!!!");
//                SystemClock.sleep(1000);
//                dismissDialog();
//                SystemClock.sleep(1000);
//                if(mCount > 0){
//                    mCount -- ;
//                    checkPermission(1);
//                }
            }

            @Override
            public void onError(Bundle bundle) {
                mFailCount ++;
                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                LogUtil.e("身份证------", msg + "!!!!!");
                Snackbar.make(mLinearLayout, "err:" + code + "--" + msg, Snackbar.LENGTH_LONG).setAction("Action", null).show();
                dismissDialog();
            }
        };
        if (packType == 0)
            SiecomDevice.readIdentityCard(taskCallback, 30*1000, true);
        else if (packType == 2){
            JSONObject jb = mDevice.readAsync(20,this);
            if(jb != null){
                LogUtil.e(TAG,"2 读二代证结果为："+ jb.toString());
                Toast.makeText(this,jb.toString(),Toast.LENGTH_SHORT).show();
            }
        } else if (packType == 1){
            JSONObject jb = mZBKInstance.getIDCardInfo(20*1000,this);
            if(jb != null){
                LogUtil.e(TAG,"1 读二代证结果为："+ jb.toString());
                Toast.makeText(this,jb.toString(),Toast.LENGTH_SHORT).show();
            }
        }else if(packType == 3){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    JSONObject jb = mUPDDevice.getIDCardInfo(10*1000,DeviceActivity.this);
                    if(jb != null){
                        LogUtil.e(TAG,"1 读二代证结果为："+ jb.toString());

                    }
                }
            }).start();

        }
    }



    /**
     * 获取指纹图像
     */
    public void getFingerImageViewPrint() {
        mFailCount=0;
        mSuccessCount = 0;
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
            pDialog = null;
        }
        View view = LayoutInflater.from(this).inflate(R.layout.layout_finger_scan, null);
        scan_line = (ImageView) view.findViewById(R.id.lockscreen_scan_line);
        upAnimation = AnimationUtils.loadAnimation(DeviceActivity.this, R.anim.push_up_in);
        upAnimation.setFillAfter(true);
        upAnimation.setAnimationListener(new UpAnimationOnListener());
        downAnimation = AnimationUtils.loadAnimation(this, R.anim.push_up_out);
        downAnimation.setFillAfter(true);
        downAnimation.setAnimationListener(new DownAnimationOnListener());
        scan_line.startAnimation(downAnimation);

        now = System.currentTimeMillis();

        SiecomDevice.readFingerPic(new DeviceCallback() {
            @Override
            public void onStart() {

                if (pDialog != null && pDialog.isShowing()) {
                    pDialog.dismiss();

                }
                pDialog = null;
                View view = LayoutInflater.from(DeviceActivity.this).inflate(R.layout.layout_finger_scan, null);
                scan_line = (ImageView) view.findViewById(R.id.lockscreen_scan_line);
                upAnimation = AnimationUtils.loadAnimation(DeviceActivity.this, R.anim.push_up_in);
                upAnimation.setFillAfter(true);
                upAnimation.setAnimationListener(new UpAnimationOnListener());

                downAnimation = AnimationUtils.loadAnimation(DeviceActivity.this, R.anim.push_up_out);
                downAnimation.setFillAfter(true);
                downAnimation.setAnimationListener(new DownAnimationOnListener());
                scan_line.startAnimation(downAnimation);

                pDialog = new MaterialDialog.Builder(DeviceActivity.this)
                        .theme(Theme.DARK)
                        .customView(view, true)
                        .title(R.string.read_fingerimg)
                        .positiveText(R.string.no)
                        .cancelable(false)
                        .dismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                /**
                                 * 取消任务；
                                 */
                                SiecomDevice.cancelCurrentTask(new DeviceCallback() {
                                    @Override
                                    public void onStart() {

                                    }

                                    @Override
                                    public void onError(Bundle bundle) {

                                    }

                                    @Override
                                    public void onSuccess(Bundle bundle) {

                                        Toast.makeText(DeviceActivity.this, bundle.getString("data"), Toast.LENGTH_SHORT).show();

                                    }

                                    @Override
                                    public void onCompleted(Bundle bundle) {

                                    }
                                }, 2000, true);


                            }
                        })
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                                dismissDialog();
                                Snackbar.make(mLinearLayout, "取消指纹后再启动最长可能需要5~7秒", Snackbar.LENGTH_LONG).setAction("Action", null).show();

                            }
                        })
                        .build();

                pDialog.show();

                Snackbar.make(mLinearLayout, "您可以放开手指了,开始传输图像", Snackbar.LENGTH_LONG).setAction("Action", null).show();
            }

            @Override
            public void onError(Bundle bundle) {
                mFailCount++;
                dismissDialog();
                Snackbar.make(mLinearLayout, "指纹图片错误", Snackbar.LENGTH_LONG).setAction("Action", null).show();
            }

            @Override
            public void onSuccess(Bundle bundle) {
                mSuccessCount++;
                dismissDialog();
                /**
                 * 获取到指纹特征码，默认使用Base64转一下
                 */
                dismissDialog();
                Bitmap bm = bundle.getParcelable("Img");
                View view = LayoutInflater.from(DeviceActivity.this).inflate(R.layout.fingerprintimage, null);
                ImageView fingerImageView = (ImageView) view.findViewById(R.id.fingerImageView);
                fingerImageView.setImageBitmap(bm);
                pDialog = new MaterialDialog.Builder(DeviceActivity.this)
                        .theme(Theme.DARK)
                        .customView(view, true)
                        .title("指纹图片")
                        .positiveText("指纹图片")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                                pDialog.dismiss();
                            }
                        })
                        .build();
                pDialog.show();

                Snackbar.make(mLinearLayout, "总耗时：" + (System.currentTimeMillis() - now) + "ms", Snackbar.LENGTH_LONG).setAction("Action", null).show();


            }

            @Override
            public void onCompleted(Bundle bundle) {
//                now = System.currentTimeMillis();
//                pDialog.setTitle("成功"+ mSuccessCount+"次，"+ "失败" + mFailCount + "次");
            }
        }, 30000, true);


    }

    /**
     * 连接设备
     */
//    private void initLink() {
//
//        SiecomDevice.connectStatusChange(new ConnectStatusCallback() {
//            @Override
//            public void onConnectStart() {
//                LogUtil.e("connectStatusChange", "onConnectStart");
//            }
//
//            @Override
//            public void onConnected() {
//                LogUtil.e("connectStatusChange", "onConnected");
//            }
//
//            @Override
//            public void onDisConnect(Throwable e) {
//                LogUtil.e("connectStatusChange", e.getMessage());
//                handler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(DeviceActivity.this, "连接已经断开", Toast.LENGTH_SHORT).show();
//                        dismissDialog();
//                    }
//                });
//
//
//            }
//        });
//
//        SiecomDevice.startConnect(device, new DeviceCallback() {
//            @Override
//            public void onStart() {
//
//            }
//
//            @Override
//            public void onError(Bundle bundle) {
//
//            }
//
//            @Override
//            public void onSuccess(Bundle bundle) {
//
//                afterLink();
//            }
//
//            @Override
//            public void onCompleted(Bundle bundle) {
//
//
//            }
//        }, true);
//
//    }


//    /**
//     * 连接成功后
//     */
//    public void afterLink() {
//        spb.progressiveStop();
//        deviceName.setTextColor(ContextCompat.getColor(DeviceActivity.this, R.color.forest_green));
//        TransitionDrawable mTransitionDrawable = new TransitionDrawable(new Drawable[]{
//                deviceIcon.getDrawable(),
//                ContextCompat.getDrawable(DeviceActivity.this, R.mipmap.connected_black)
//        });
//        mTransitionDrawable.setCrossFadeEnabled(true);
//        mTransitionDrawable.startTransition(1000);
//        deviceIcon.setImageDrawable(mTransitionDrawable);
//        addUI();
//    }
    TextView mTrackTV;
    private void getSingature() {
        Log.e("read", "getSingature");
        now = System.currentTimeMillis();
        DeviceCallback taskCallback = new DeviceCallback() {
            @Override
            public void onStart() {
                Snackbar.make(mLinearLayout, getResources().getString(R.string.read_signature), Snackbar.LENGTH_LONG).setAction("Action", null).show();
                pDialog = new MaterialDialog.Builder(DeviceActivity.this)
                        .title(R.string.read_signature)
                        .backgroundColor(getResources().getColor(R.color.white))
                        .content(R.string.please_wait)
                        .progress(true, 0)
                        .progressIndeterminateStyle(true)
                        .positiveText(R.string.no)
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                                dismissDialog();
                                SiecomDevice.cancelCurrentTask(new DeviceCallback() {
                                    @Override
                                    public void onStart() {
                                    }

                                    @Override
                                    public void onError(Bundle bundle) {
                                    }
                                    @Override
                                    public void onSuccess(Bundle bundle) {
                                        Toast.makeText(DeviceActivity.this, bundle.getString("data"), Toast.LENGTH_SHORT).show();
                                    }
                                    @Override
                                    public void onCompleted(Bundle bundle) {
                                    }
                                }, 2000, true);
                            }
                        })
                        .dismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {

                            }
                        })
                        .build();
                pDialog.show();
            }

            @Override
            public void onSuccess(Bundle bundle) {
                dismissDialog();
                View view = LayoutInflater.from(DeviceActivity.this).inflate(R.layout.signature_dialog, null);
                Bitmap signature = bundle.getParcelable("data");
                ImageView imageView = (ImageView) view.findViewById(R.id.signatureImageView);
                mTrackTV = (TextView) view.findViewById(R.id.tv_track_data);
                imageView.setImageBitmap(signature);
//                saveBitmapTofile(signature,path + "phonessssssssssss.png");
                pDialog = new MaterialDialog.Builder(DeviceActivity.this)
                        .theme(Theme.DARK)
                        .customView(view, true)
                        .title(R.string.read_signature)
                        .positiveText(R.string.no)
                        .cancelable(true)
                        .dismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {

                            }
                        })
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog materialDialog, DialogAction dialogAction) {
                                dismissDialog();

                            }
                        })
                        .build();
                pDialog.show();

            }

            @Override
            public void onCompleted(Bundle bundle) {



                final ArrayList<Point> mPointList = (ArrayList) bundle.getParcelableArrayList("NoPasswordTrack");
//                Point mPoint = mPointList.get(1);
//                Log.e("GJ","指压数据："+mPoint.getT()+"\n坐标X："+mPoint.getX()+"\n坐标Y："+mPoint.getY());

                handler.postAtTime(new Runnable() {
                    @Override
                    public void run() {
//                        Toast.makeText(DeviceActivity.this, DisplayTrackData(mPointList), Toast.LENGTH_LONG).show();
//                        Log.e("GJ","轨迹数据为"+DisplayTrackData(mPointList));
                        if(null != mTrackTV ){
                            mTrackTV.setText(SiecomDevice.DisplayTrackData(mPointList));
                        }
                    }
                },1000);

//                Toast.makeText(DeviceActivity.this,"指压数据：").show();
                //这是轨迹加密密文
//                byte[] data = bundle.getByteArray("data");
//                LogUtil.e("GJ","date:--->"+ByteTool.byte2hex(data));
//                //这是解密后的,使用写上的密钥解密
//                data = SMUtil.SM4DecryptECB(data, sm4key);
////                String dedata = ByteTool.byte2hex(data);
////                   LogUtil.e("dedata",dedata);
//
//
//
//                List<Point> list = ParsePoint.parse(data);
//                /**
//                 * X Y最大值为6156 10952 T 最大为 4095,
//                 * 所以需要对应屏幕需要显示的画布大小算，
//                 */
//                LogUtil.e("GJ","list:--->"+list.size()+"--");
//                for (int i = 0; i < list.size(); i++) {
//                    LogUtil.e("i", i + "-");
//                    SystemClock.sleep(1);
//                    LogUtil.e("GJ", "pointX--"+list.get(i).getX() + "-");
//                    LogUtil.e("GJ", "pointY--"+list.get(i).getY() + "-");
//                    LogUtil.e("GJ", "pointT--"+list.get(i).getT() + "-");
//
//
//                }

            }

            @Override
            public void onError(Bundle bundle) {
                int code = bundle.getInt("code");
                String msg = bundle.getString("message");
                Log.e("签名------", msg + "!!!!!");
                Snackbar.make(mLinearLayout, "err:" + code + "--" + msg, Snackbar.LENGTH_LONG).setAction("Action", null).show();

                dismissDialog();
            }
        };
        if(packType == 0){
            SiecomDevice.getSignature(taskCallback, 90*1000, true);
        }
        else if(packType == 1){
            JSONObject jb = mZBKInstance.getHWScreenData(60*1000);
            LogUtil.e(TAG,"mZBKInstance.getHWScreenData == " + jb.toString());
        }else if (packType == 2){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    JSONObject jb = mDevice.getHWScreenData(30);
                    LogUtil.e(TAG,"mInstance.getHWScreenData 2 == " + jb.toString());
                }
            }).start();

        }else if (packType == 3){
            new Thread(new Runnable() {
                @Override
                public void run() {
//                    JSONObject jb = mUPDDevice.getSignature(30*1000,"/sdcard/sign.png","/sdcard/xmlPath",false);
//                    mUPDDevice.closeHWScreen();
                    JSONObject jb = mUPDDevice.getHWScreenData(30*1000);
                    LogUtil.e(TAG,"mUPDDevice.getHWScreenData == " + jb.toString());
                    try {
                        File file = new File(jb.getString("picture"));
                        LogUtil.e(TAG,"filelength == " + file.length());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }

    }


    /**
     * 监听蓝牙状态
     */
    private void connectStatusListen() {

        SiecomDevice.connectStatusChange(new ConnectStatusCallback() {
            @Override
            public void onConnectStart() {
                Log.e("connectStatusChange", "onConnectStart");
            }

            @Override
            public void onConnected() {
                Log.e("connectStatusChange", "onConnected");
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(DeviceActivity.this, "已连接", Toast.LENGTH_SHORT).show();
                        dismissDialog();
                    }
                });
            }

            @Override
            public void onDisConnect(Throwable e) {
                Log.e("connectStatusChange", e.getMessage());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(DeviceActivity.this, "连接已经断开", Toast.LENGTH_SHORT).show();
                        dismissDialog();
                    }
                });


            }
        });
    }

    /**
     * 连接设备
     */
    private void initLink() {

        connectStatusListen();
        int ret = -1;
        if (packType == 1)
            ret = mZBKInstance.openDevice(this,1);
        if (packType == 2)
            ret = mDevice.openDevice(this,1);
        if (packType == 3){
            ret = mUPDDevice.openDevice(this,1);
//            getBattaryInfo();
        }

        LogUtil.e(TAG,"蓝牙连接 ret = " + ret);
        if(ret == 0){
            afterLink();
        }
        if (packType == 0){
            SiecomDevice.startConnect(device, new DeviceCallback() {
                @Override
                public void onStart() {

                }

                @Override
                public void onError(Bundle bundle) {

                }

                @Override
                public void onSuccess(Bundle bundle) {

                    afterLink();


                }

                @Override
                public void onCompleted(Bundle bundle) {


                }
            }, true);
        }


    }

    private  void getBattaryInfo(){
        int[] infos = mUPDDevice.getBatteryInfo();
        LogUtil.e(TAG,"getBatteryInfo == " + infos[0] + infos[1] +  infos[2] );

        String id = mUPDDevice.getDeviceSerialID();
        LogUtil.e(TAG,"getDeviceSerialID == " + id );
    }
    /**
     * 连接设备成功后改变UI
     */
    public void afterLink() {
        spb.progressiveStop();
        deviceName.setTextColor(ContextCompat.getColor(DeviceActivity.this, R.color.forest_green));
        TransitionDrawable mTransitionDrawable = new TransitionDrawable(new Drawable[]{
                deviceIcon.getDrawable(),
                ContextCompat.getDrawable(DeviceActivity.this, R.mipmap.connected_black)
        });
        mTransitionDrawable.setCrossFadeEnabled(true);
        mTransitionDrawable.startTransition(1000);
        deviceIcon.setImageDrawable(mTransitionDrawable);
        addUI();

        if(packType == 1){
            LogUtil.e(TAG,"serialid 1 == " + mZBKInstance.getDeviceSerialID() + " isConnect == " + mZBKInstance.isConnect());
        }
        if (packType == 2)
            LogUtil.e(TAG,"serialid 2 == " + mDevice.getDeviceSerialID() + " isConnect == " + mDevice.isConnect());
        if (packType == 3)
            LogUtil.e(TAG,"mUPDDevice.getDeviceSerialID == " + mUPDDevice.getDeviceSerialID());
    }


    public void disConnectBlueDevice(){
        SiecomDevice.disConnect(new DeviceCallback() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Bundle bundle) {

            }

            @Override
            public void onSuccess(Bundle bundle) {

            }

            @Override
            public void onCompleted(Bundle bundle) {

            }
        }, true);
    }

    public void disConnectBTP350(){
       int ret =  mZBKInstance.closeDevice(this,1);
       LogUtil.e(TAG,"disConnectBTP350 ret = " + ret);
    }
    /**
     * UI界面
     */
    private void addUI() {
        /*  身份证 */
        LinearLayout rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                /**
                 * 读取身份证需要在sd卡上写入授权文件，6.0以上需要检查权限
                 */
                checkPermission(1);


            }
        });
        mLinearLayout.addView(rl);

        /*  指纹 */
        rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
        TextView tv = (TextView) rl.findViewById(R.id.read_id);
        tv.setText(getResources().getString(R.string.read_finger));
        ImageView iv = (ImageView) rl.findViewById(R.id.id_icon);
        iv.setImageResource(R.mipmap.fingerprint);

        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                readFingerPrint();
            }

        });


        mLinearLayout.addView(rl);


        rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
        TextView finger1 = (TextView) rl.findViewById(R.id.read_id);
        finger1.setText(getResources().getString(R.string.read_fingerimg));
        ImageView fingers1 = (ImageView) rl.findViewById(R.id.id_icon);
        fingers1.setImageResource(R.mipmap.fingerprint);

        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getFingerImageViewPrint();
            }
        });
        mLinearLayout.addView(rl);

        rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
        TextView finger = (TextView) rl.findViewById(R.id.read_id);
        finger.setText(getResources().getString(R.string.read_signature));
        ImageView fingers = (ImageView) rl.findViewById(R.id.id_icon);
        fingers.setImageResource(R.mipmap.brush);

        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getSingature();

            }
        });
        mLinearLayout.addView(rl);

        /*密码键盘*/
        rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
        tv = (TextView) rl.findViewById(R.id.read_id);
        tv.setText(getResources().getString(R.string.keyPin));
        iv = (ImageView) rl.findViewById(R.id.id_icon);
        iv.setImageResource(R.mipmap.keyboard);

        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showKeyDialog();

            }
        });
        mLinearLayout.addView(rl);


          /*银行卡*/
        rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
        tv = (TextView) rl.findViewById(R.id.read_id);
        tv.setText(getResources().getString(R.string.bankCard));
        iv = (ImageView) rl.findViewById(R.id.id_icon);
        iv.setImageResource(R.mipmap.ic_credit_card);

        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showCardDialog();

            }
        });
        mLinearLayout.addView(rl);

        rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
        tv = (TextView) rl.findViewById(R.id.read_id);
        tv.setText(getResources().getString(R.string.other));
        iv = (ImageView) rl.findViewById(R.id.id_icon);
        iv.setImageResource(R.mipmap.settings_black);

        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消操作
                if(packType == 3){
                    int ret = mUPDDevice.cancelReadIDCard();
                    LogUtil.e(TAG,"cancelReadIDCard == " + ret);
//                    int ret = mUPDDevice.cancelReadFp();
//                    LogUtil.e(TAG,"cancelReadFp == " + ret);
//                    int ret = mUPDDevice.closeHWScreen();
//                    LogUtil.e(TAG,"closeHWScreen == " + ret);

                    //升级操作
//                    final String path = "sdcard/HostV1.4.7.6.apk";
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                           boolean suc = mUPDDevice.updateDevice(path);
//                            LogUtil.e(TAG,"updateDevice == " + suc);
//                        }
//                    }).start();

                }
                showOtherDialog();
            }
        });
        mLinearLayout.addView(rl);

        //测试其他功能
//        rl = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.item_card, null);
//        tv = (TextView) rl.findViewById(R.id.read_id);
//        tv.setText(getResources().getString(R.string.other));
//        iv = (ImageView) rl.findViewById(R.id.id_icon);
//        iv.setImageResource(R.mipmap.settings_black);

//        rl.findViewById(R.id.item_card).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //取消操作
//                if(packType == 3){
//                    int ret = mUPDDevice.openDevice(DeviceActivity.this,1);
//                    LogUtil.e(TAG,"openDevice == " + ret);
//
//                }
//            }
//        });
//        mLinearLayout.addView(rl);

        //------------------------
        //initKeySignPad();
        //-------------------------
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_identify);

        //日志开关
        LogUtil.setLogEnabled(true);
        LogUtil.setLog2File(false);

        deviceName = (TextView) findViewById(R.id.device_name);
        deviceMac = (TextView) findViewById(R.id.device_mac);

        mType = getIntent().getStringExtra("type");
        if(mType.equals("1")){ //蓝牙设备
            device = getIntent().getParcelableExtra("Device");
            deviceName.setText(device.getName());
            deviceMac.setText(device.getAddress());


            mZBKInstance = new ZBKDeviceProtocol(this,device.getName());
            mUPDDevice = new UPDDeviceProtocol(this,device.getName());

        }else if (mType.equals("2")){
            mUsbDevice = getIntent().getParcelableExtra("Device");
            deviceName.setText("A108Plus");
//            deviceName.setText(mUsbDevice.getProductName());
            deviceMac.setText("USB连接");
        }
        deviceVersion = (TextView) findViewById(R.id.device_version);

        mDevice = SiecomDeviceProtocol.getInstance();

        power = (TextView) findViewById(R.id.power);
        deviceIcon = (ImageView) findViewById(R.id.device_icon);
        spb = (SmoothProgressBar) findViewById(R.id.spb);
        spb.setVisibility(View.INVISIBLE); // wait for runnable
        mLinearLayout = (LinearLayout) findViewById(R.id.info_scroll);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                spb.setVisibility(View.VISIBLE);

                /*
                  首先连接蓝牙
                 */
                if(mType.equals("1")){
                    initLink();
                }else {
                    afterLink();
                }
//                afterLink();
            }
        },200);

    }

    /**
     * 取消对话框
     */
    public void dismissDialog() {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    /**
     * android API23以上需要检查权限
     */
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;


    public void checkPermission(int code) {
        Log.e("click", "checkPermission");
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    code);
        } else {
            if (code == MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) {
                readIDcard();
            } else {
//                updateBin();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) {

            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Toast.makeText(this, "Permission ok", Toast.LENGTH_SHORT).show();

                readIDcard();

            } else {

                // Permission Denied
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        } else {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Toast.makeText(this, "Permission ok", Toast.LENGTH_SHORT).show();

//                updateBin();

            } else {

                // Permission Denied
                Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }

        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    @Override
    public void onDestroy() {

        super.onDestroy();
        if (packType == 0)
            disConnectBlueDevice();

        if (packType == 1)
            disConnectBTP350();

        if (packType == 2){
            int ret = mDevice.closeDevice(this,0);
            LogUtil.e(TAG,"closeDevice == " + ret);
        }
        if (packType == 3){
            mUPDDevice.closeDevice(this,0);
        }

    }

    /**
     * 指纹动画效果
     * 上下扫描
     */
    private class DownAnimationOnListener implements Animation.AnimationListener {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {

            scan_line.startAnimation(upAnimation);

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            // TODO Auto-generated method stub

        }

    }

    private class UpAnimationOnListener implements Animation.AnimationListener {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {

            scan_line.startAnimation(downAnimation);

        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }

    }


}




